package com.edu.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.backend.dao.AdminDao;
import com.edu.backend.entity.Admin;
import com.edu.backend.entity.AdminDTO;
import com.edu.backend.entity.User;
import com.edu.backend.exception.EduException;
import com.edu.backend.service.AdminService;
import com.edu.backend.utils.JwtUtils;
import com.edu.backend.utils.MD5;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yanjunfeng
 * @Description: TODO
 * @Date: Created in 上午11:47 2023/6/19
 * @Modified By:
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, Admin> implements AdminService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    AdminDao adminDao;

    @Override
    public String login(Admin admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        QueryWrapper<Admin> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        Admin adminDetails = this.getOne(userQueryWrapper);
        if (adminDetails == null || !MD5.encrypt(password).equals(adminDetails.getPassword()))
            throw new EduException("用户名或密码错误!");
        assert adminDetails != null;
        String jwtToken = JwtUtils.getJwtToken(adminDetails.getId(), adminDetails.getUsername());
        AdminDTO adminDTO = new AdminDTO();
        BeanUtils.copyProperties(adminDetails, adminDTO);
        // 加入到redis中
        stringRedisTemplate.opsForValue().set(jwtToken, JSON.toJSONString(adminDTO), 1, TimeUnit.DAYS);
        return jwtToken;
    }
    @Override
    public AdminDTO getAdminInfo(String token) {
        String userJson = stringRedisTemplate.opsForValue().get(token);
        return JSON.parseObject(userJson, AdminDTO.class);
    }

    @Override
    public Boolean updateAdmin(Admin admin) {
        admin.setPassword(MD5.encrypt(admin.getPassword()));
        Boolean result = this.updateById(admin);
        return result;
    }

    @Override
    public Integer updateAvatarById(String avatar,Integer id) {

        Integer result=adminDao.updateAvatar(avatar,id);
        return result;
    }


    @Override
    public void logout(String token) {
        // 从redis中将token移除
        stringRedisTemplate.delete(token);
    }

    @Override
    public Admin getAdmin(Integer id) {
        Admin admin = this.getById(id);
        return admin;
    }
}
